package com.itfreer.arcgis.edit;

import android.os.Bundle;
import android.os.Message;

import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.itfreer.arcgis.utils.FeatureTableUtils;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.utils.common.StringUtils;

import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;

/**
 * 处理编辑后的值处理
 */
public class ValueOption {

    /**
     * 处理默认值
     * @param featureLayer
     * @param attribute
     */
    public static void setDefultValue(FeatureLayer featureLayer, Map<String, Object> attribute, ProjectEntity config){
        String defaultValue = config.getDefaultValue();
        if (StringUtils.IsNullOrEmpty(defaultValue)) {
            return;
        }

        try {
            // 添加异常捕捉，防止默认配置报错
            JSONObject jsonObject = new JSONObject(defaultValue);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String fieldName = keys.next();
                // 字段名必须存在，并且字段不能是系统字段
                if (FeatureTableUtils.IsFieldExist(featureLayer.getFeatureTable(), fieldName)
                        && !FeatureTableUtils.IsSystemField(featureLayer.getFeatureTable(), fieldName)) {
                    attribute.put(fieldName, jsonObject.get(fieldName));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据图形面积，更新area字段
     */
    public static void updateArea(FeatureLayer featureLayer, String areaField, Map<String, Object> attribute, Geometry geometry){
        if(geometry.getGeometryType()== GeometryType.POLYLINE) {
            Double lengthMi = GeometryEngine.length((Polyline)geometry);
            lengthMi = (double)Math.round(lengthMi*100)/100l; // 单位面
            // 字段名必须存在，并且字段不能是系统字段
            if (FeatureTableUtils.IsFieldExist(featureLayer.getFeatureTable(), areaField)
                    && !FeatureTableUtils.IsSystemField(featureLayer.getFeatureTable(), areaField)) {
                attribute.put(areaField, lengthMi);
            }
        }
        else if(geometry.getGeometryType()== GeometryType.POLYGON) {
            Double mjMi = GeometryEngine.area((Polygon) geometry);
            mjMi = Math.abs(mjMi); //单位平方米
            mjMi = mjMi / 10000; //单位公顷
            mjMi = (double)Math.round(mjMi*10000)/10000l; // 4位小数
            // 字段名必须存在，并且字段不能是系统字段
            if (FeatureTableUtils.IsFieldExist(featureLayer.getFeatureTable(), areaField)
                    && !FeatureTableUtils.IsSystemField(featureLayer.getFeatureTable(), areaField)) {
                attribute.put(areaField, mjMi);
            }
        }
    }
}
